require 'rubygems'
require 'hpricot'

class Gadget
  
  attr_accessor :xml_spec, :spec_url, :title
  
  
  def initialize(spec_url)
    @spec_url = spec_url
    @xml_spec = XmlSpec.new
    @xml_spec.read(@spec_url)
    @title = @xml_spec.title
  end
  
  
  def self.get_local_spec_filenames
    return Dir.glob("public/gadget_specs/*")
  end
  
  
  # Returns an array of gadgets that are found in the local public/gadget_specs directory
  def self.find_all_local(gadget_server)
    results = []
    specs = Dir.glob("public/gadget_specs/*")
    specs.each do |spec|
      # make sure we only process xml spec files
      if spec.index('.xml')
        gadget = Gadget.new(gadget_server + spec.sub("public", ''))
        results.push(gadget)
      end
    end
    return results
  end
  
  
 # def to_json
 #   return "{'spec_url':'#(@spec_url)', 'container_id':'default', 'title':'Gadget Title'}"
 # end
  
  
  def render(view)
    if @xml_spec.contents[0]['type'] == 'url'
      # if the gadget type is 'url', just create an iframe and let the browser
      # pull in the application.  This takes advantage of browser proxy settings.
      content = '<iframe src="' + @xml_spec.contents[0]['href'] + '" width="400" height="600" />'      
    else
      # Gadget is 'html' type
      content = render_content(view)
    end
    return content
  end
  
  
  private
  
  def render_content(view)
    spec_content = @xml_spec.get_content_for_view(view)
    @content = ''
    @content = '<head>';
    @content = @content + write_core_js
    @content = @content + add_features
    @content = @content + '</head><body>'
    @content = @content + rewrite(spec_content)
    @content = @content + '<script>'
    @content = @content + 'gadgets.util.runOnLoadHandlers();'
    @content = @content + '</script></body>'
    return @content
  end
  
  
  def write_core_js
    content = ''
    #content = content + '<script src="/javascripts/core_container.js"></script>'
    content = content + '<script src="/javascripts/core/core.js"></script>'
    content = content + '<script src="/javascripts/core/config.js"></script>'
    content = content + '<script src="/javascripts/core/json.js"></script>'
    content = content + '<script src="/javascripts/core/util.js"></script>'
    content = content + '<script src="/javascripts/core/prefs.js"></script>'
    content = content + '<script src="/javascripts/core/auth.js"></script>'
    content = content + '<script src="/javascripts/core/auth-init.js"></script>'
    content = content + '<script src="/javascripts/core/legacy.js"></script>'
    content = content + '<script src="/javascripts/core/rpc.js"></script>'
    content = content + '<script src="/javascripts/core/io.js"></script>'
    
    
    content = content + '<script src="/javascripts/container.js"></script>'
    content = content + '<script src="/javascripts/gadgets.js"></script>'
    return content
  end
  
  
  
  # Add the features that are required by this gadget.  Features are 
  # implemented in JavaScript libraries.
  def add_features
    result = ''
    # add in these features for now
    features_to_add = [
      {'name'=>'views',
       'libs' => ['rpc/rpc.js', 'views/views.js']},
      {'name'=>'dynamic-height',
       'libs' => ['dynamic-height/dynamic-height.js']},    
      {'name'=>'setprefs',
       'libs' => ['setprefs/setprefs.js']}
    ]
    
    features_to_add.each do |feature|
      feature = GadgetFeature.new(feature['name'], feature['libs'])
      result = result + feature.get_js_libs
    end
    
    #feature = GadgetFeature.new('analytics')
    #feature.get_js_libs()
    
    # Things break with these 2 lines uncommented
    #result = result + '<script src="http://www.google-analytics.com/urchin.js"/>'
    #result = result + '<script src="http://www.google.com/ig/lib/libanalytics.js"/>'
    
    return result
  end
  
  
  # Rewrite the internal script tags to point to the correct directory
  def rewrite(content)    
    content = rewrite_script_tags(content)  
    return content
  end
  
  
  # Rewrite included JavaScript tags so that they load from the correct location
  # prepend 'gadget_specs/test/'
  def rewrite_script_tags(content)
    doc = Hpricot(content)  
    doc.search("//script").each do |script|
      if script.attributes['src']
        content = '<script src="/gadget_specs/' + script.attributes['src'] + '"></script>' + content
      end
    end
    return content
  end
  
end